/**
 * @help 运行时配置
 * **/
import { history } from 'umi';
import { getCookie } from '@/utils/cookie';
import { message } from 'antd';
import { menuConfig } from '@/config/menuConfig';
import _ from 'lodash';

const renderRoutes: (data: any) => any = (data) => {
  return _.flatMapDeep(
    _.map(data, (item, key) => {
      if (item.children) {
        return renderRoutes(item.children);
      }
      return item;
    }),
  );
};

const menu_item_group: (data: any) => any = (data) => {
  return _.flatMapDeep(
    _.map(data, (item, key) => {
      if (!_.isArray(item) && typeof item === 'object') {
        const newData = [];
        for (let i in item) {
          newData.push(renderRoutes(item[i]));
        }
        return newData;
      } else {
        return renderRoutes(item);
      }
    }),
  );
};

// 动态添加路由(直接修改routes,不需要返回自)
export function patchRoutes({ routes }: any) {
  const cookies = getCookie();

  if (cookies.username === 'admin') {
    const obj_keys: string[] = Object.keys(menuConfig);
    const adminRoutes = _.flattenDeep(
      _.map(obj_keys, (item, key) => {
        return menuConfig[item];
      }),
    );

    _.forEach(menu_item_group(adminRoutes), (item, key) => {
      routes[0].routes[1].routes.unshift(item);
    });
  }
}

// 覆写 render
// 会在 patchRoutes 之前执行
export function render(oldRender: Function) {
  // 挂载应用(渲染)
  oldRender();
}

// 在初始加载和路由切换时做一些事情。
export function onRouteChange({ location, matchedRoutes }: any) {
  if (matchedRoutes.length) {
    document.title =
      matchedRoutes[matchedRoutes.length - 1].route.title || 'UmiJS';
  }
  const cookies = getCookie();
  const username = cookies.username;
  if (!username && location.pathname !== '/login') {
    history.push('/login');
    message.destroy('#1');
    message.error({
      content: '登录状态过期!',
      key: '#1',
    });
  }
  if (location.pathname === '/' && username) {
    switch (username) {
      case 'admin':
        history.push('/admin/docs/home');
        break;
      default:
        history.push('/admin');
        break;
    }
  } else if (location.pathname === '/' && !username) {
    history.push('/login');
  } else if (location.pathname === '/login' && username) {
    history.goBack();
  }
}
